package com.gg.common.result;


/**
 * 前端返回页面的统一操作对象
 * 为的是防止数据类型不一致，使用此类可以统一返回类型，方便前端拿到数据展示
 *
 * @author chenjunjia
 * @since 2022-04-02
 */
public class CommonResult<T> {

    private Integer code;
    private String message;
    private T data;

    public CommonResult() {
    }

    public CommonResult(ResultCodeEnum resultCodeEnum) {
        this.code = resultCodeEnum.getCode();
        this.message = resultCodeEnum.getMessage();
    }

    public CommonResult(ResultCodeEnum resultCodeEnum, T data) {
        this.code = resultCodeEnum.getCode();
        this.message = resultCodeEnum.getMessage();
        this.data = data;
    }

    protected static <T> CommonResult<T> build(T data){
        CommonResult<T> commonResult = new CommonResult<T>();
        if (data != null){
            commonResult.setData(data);
        }
        return commonResult;
    }

    public static <T> CommonResult<T> build(T data,ResultCodeEnum resultCodeEnum){
        CommonResult<T> commonResult = new CommonResult<T>();
        commonResult.build(data);
        commonResult.setCode(resultCodeEnum.getCode());
        commonResult.setMessage(resultCodeEnum.getMessage());
        return commonResult;
    }

    public static <T> CommonResult<T> ok(){
        return CommonResult.ok(null);
    }

    public static <T> CommonResult<T> ok(T data){
        return CommonResult.build(data,ResultCodeEnum.SUCCESS);
    }

    public static <T> CommonResult<T> fail(T data){
        return CommonResult.build(data,ResultCodeEnum.FAIL);
    }

    public static <T> CommonResult<T> fail(){
        return CommonResult.fail(null);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "CommonResult{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
